// pages/contest/upload/upload.js
import {
  observer
} from '../../../libs/observer';
import {
  toJS,
  action
} from '../../../libs/mobx';
import {  communityAlilog } from '../../../utils/community_util.js';
import ContestStore from '../contestStore.js';
import Store from './store.js';
import LoginStore from '../../login/store.js';
import EditStore from '../../editPhotocommunity/store.js';

let groupPhoto = [];
let coverObj = {};

import {
  stringify,
  ossuploadurl,
  reqHeader,
  proxy
} from '../../../utils/util.js';

let uploadNum = 0

Page(observer({
  props: {
    store: Store
  },

  /**
   * 页面的初始数据
   */
  data: {
    files: [],
    bb: {
      a: 1,
      b: 2,
      c: 3
    }
  },
  goBack() {
    // wx.redirectTo({
    //   url: '/pages/community/index',
    // })
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];
    prevPage.setData({
      showTheme:false,
      })
    wx.navigateBack({
      delta: 1
    })
    
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let pages = getCurrentPages();
    let contestPage = pages[pages.length - 2];
    contestPage.setData({
      freshMark: true
    });
    let me = this;
    let names = [];
    let filesData = [];
    this.props.store.filePaths.forEach((item, index) => {
      console.log(item);
      if (typeof item === 'string') {
        let pathdata = {}
        pathdata.path = item;
        filesData[index] = pathdata;
        names.push(item);
      } else {
        filesData[index] = item;
        names.push(item.path);
      }
      
      
    })
    this.setData({
      files: filesData
    })
    if (names.length) {
      console.log(names);
      this.uploadFun(names);
    }
  },
  reloadImg:function(e){
    let names = [];
    names.push(e.currentTarget.dataset.names);
    this.uploadFun(names);
  },
  uploadFun: function (names){
    console.log(names);
    let me = this;
    wx.request({
      url: `${proxy}/community/v2/upload/ossInfo`,
      data: {
        access_token: LoginStore.userInfo.access_token,
        originalNames: JSON.stringify(names),
        uploadType: 'photo'
      },
      header: reqHeader,
      success: function (res) {
        if (res.statusCode != 200) {
          return;
        }
        res = res.data;
        if (res.status == 200) {
          res.data.forEach((_item, _index) => {
            console.log(_item);
            me.uploadImage({
              item: _item,
              index: _index,
              ossInfo: res.ossInfo,
              filePath: _item.fileName,
              ossId: _item.ossId
            })
          });
        } else {
          console.log(res.message);
        }
      }
    })
  },
  uploadImage(params) {
    let me = this;
    wx.getImageInfo({
      src: params.filePath,
      success: function(imgInfo) {
        let _index = params.index;
        var ossInfo = params.ossInfo;
        // const aliyunFileKey = "lyby/" + params.filePath.replace('wxfile://', '');
        let upload_task = wx.uploadFile({
          url: ossInfo.host,
          filePath: params.filePath,
          name: 'file', //必须填file
          formData: {
            'key': params.ossId,
            'policy': ossInfo.policy,
            'OSSAccessKeyId': ossInfo.accessid,
            'signature': ossInfo.signature,
            'success_action_status': '200',
          },
          success: function(res) {
            if (res.statusCode != 200) {
              console.log(new Error('上传错误:' + JSON.stringify(res)))
              return;
            }
            // debugger;
            console.log('上传图片成功', res);
            uploadNum++;
            console.log(uploadNum);
            console.log(me.data.files.length);
            if (me.data.files.length >1){
              groupPhoto.push({
                id: params.item.id,
                url: params.item.url,
                width: imgInfo.width,
                height: imgInfo.height,
                description: EditStore.descObj[params.filePath]
              });
              if (params.filePath === EditStore.coverPath){
                coverObj={
                  width: imgInfo.width,
                  height: imgInfo.height,
                  url: params.item.url
                }
              }
            }
            let postData = {};
            if (uploadNum == me.data.files.length){
              
              if (uploadNum == 1){
                postData = {
                  tribeId: wx.getStorageSync('tribeId'),
                  version: 1,
                  // contestCategoryId: Store.selectedCategoryId,
                  jsonData: stringify([Object.assign({
                    width: imgInfo.width,
                    height: imgInfo.height,
                    "extraInfo": [],
                    "extendedField": {
                      waterMark: 'sw'
                    }, //任意数据都可插入
                    "openState": "profile", //公开状态
                    "title": EditStore.titleValue, //标题
                    "description": EditStore.descValue, //描述
                    "tags": "", //关键词
                    "categoryId": "0", //分类
                    "doTsa": false
                  }, params.item)])
                }
                console.log('投稿', postData);
                wx.request({
                  url: `${proxy}/community/v2/photo/save?access_token=${LoginStore.userInfo.access_token}`,
                  method: 'post',
                  data: postData,
                  header: Object.assign({
                    'content-type': 'application/x-www-form-urlencoded',
                    access_token: LoginStore.userInfo.access_token
                  }, reqHeader),
                  success: function (_res) {
                   
                    wx.showToast({
                      title: '投稿成功',
                      icon: 'success',
                      duration: 1000
                    })
                    setTimeout(function () {
                      me.goBack();
                    }, 1000)
                    //埋点 投稿成功
                    communityAlilog('mini-program-tribe-profile-submit-completed');
                    //埋点 投稿成功
                    uploadNum = 0
                  },
                  fail: function (e) {
                    console.log(e);
                  }
                })
              }else{
                postData = {
                  resourceType: 2,
                  // contestCategoryId: Store.selectedCategoryId,
                  tribeId: wx.getStorageSync('tribeId'),
                  jsonData: stringify(Object.assign({
                    "openState": "profile", //公开状态
                    "title": EditStore.titleValue, //组图标题
                    "description": EditStore.descValue, //组图描述
                    "tags": "", //关键词
                    "categoryId": "0", //分类,
                    "photos": groupPhoto
                  },coverObj))
                }
                console.log('投稿', postData);
                wx.request({
                  url: `${proxy}/community/v2/groupPhoto/save?access_token=${LoginStore.userInfo.access_token}`,
                  method: 'post',
                  data: postData,
                  header: Object.assign({
                    'content-type': 'application/x-www-form-urlencoded',
                    access_token: LoginStore.userInfo.access_token
                  }, reqHeader),
                  success: function (_res) {
                    
                    groupPhoto = [];
                    uploadNum = 0;
                    wx.showToast({
                      title: '投稿成功',
                      icon: 'success',
                      duration: 1000
                    })
                   
                    setTimeout(function () {
                      me.goBack();
                    }, 1000)
                    //埋点 投稿成功
                    communityAlilog('mini-program-tribe-profile-submit-completed');
                    //埋点 投稿成功
                  },
                  fail: function (e) {
                    console.log(e);
                  }
                })
              }

              
            }
            
          },
          fail: function(err) {
            me.data.files[_index].progress = 0;
            me.data.files[_index].uploadErrorTip = true;
            me.setData({
              files: me.data.files
            });
            console.log(err)
          },
        })

        upload_task.onProgressUpdate((res) => {
          me.data.files[_index].progress = res.progress;
          me.setData({
            files: me.data.files
          })
          //Store.setFileProcess(_index, res.progress);
          //me.props.store.filePaths[_index].progress = res.progress;
          //console.log(toJS(me.props.store.filePaths))
        });
      }
    })


  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function() {

  // }
}))